//
//  HomeBottomView.m
//  KEREN
//
//  Created by MW on 2023/3/20.
//

#import "HomeBottomView.h"
#import "DeviceLocationVC.h"
#import "ElectronicfenceVC.h"
#import "DeviceShareVC.h"
#import "DeviceNavcationVC.h"
#import "DeviceCyclingRecordVC.h"
#import "ServiceNetworkVC.h"
#import "KeRenHCollectCell.h"

@interface HomeBottomView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectionV;
@property (nonatomic, strong) UIButton *searchBtn;
@property (nonatomic, strong) UIButton *on_offBtn;
@property (nonatomic, strong) UIButton *xiaokeBtn;
@property (nonatomic, strong) UIImageView *firingImageView;
@property (nonatomic, assign) BOOL isOn;
@property (nonatomic, assign) BOOL isLoding;
@property (nonatomic, assign) int contenting;
@property (nonatomic, strong) NSMutableArray *dataArray;
@end


@implementation HomeBottomView
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(UICollectionView *)collectionV{
    if(!_collectionV){
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsZero;
        _collectionV = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionV.delegate = self;
        _collectionV.dataSource = self;
        _collectionV.showsHorizontalScrollIndicator = NO;
        _collectionV.showsVerticalScrollIndicator   = NO;
        _collectionV.backgroundColor = [UIColor clearColor];
        [_collectionV registerNib:[UINib nibWithNibName:@"KeRenHCollectCell" bundle:nil] forCellWithReuseIdentifier:@"KeRenHCollectCell"];
        [self addSubview:_collectionV];
        [_collectionV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24);
            make.width.offset(DEVICE_WIDTH-24);
            make.height.offset(72);
            make.bottom.offset(-20);
        }];
    }
    return _collectionV;
}

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        [self setViewLayout];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changePowerStatus:) name:BLUETOOTHPOWERSTATUSCHANGE object:nil];
    }
    return self;
}

-(void)setViewLayout{
    _isLoding = NO;
    _on_offBtn = [UIButton setButtonWithImage:@"Device_on" cornerRadius:50 backColor:[UIColor clearColor]];
    [self addSubview:_on_offBtn];
    [_on_offBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.bottom.equalTo(self.collectionV.mas_top).offset(-20);
        make.width.height.offset(100);
    }];
    _on_offBtn.layer.borderWidth = 8;
    _on_offBtn.layer.borderColor = rgba(1, 1, 1, 0.4).CGColor;
    [_on_offBtn addTarget:self action:@selector(firing) forControlEvents:UIControlEventTouchUpInside];
    
    _firingImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Device_oning"]];
    [self addSubview:_firingImageView];
    [_firingImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.bottom.equalTo(self.collectionV.mas_top).offset(-20);
        make.width.height.offset(100);
    }];
    _firingImageView.alpha = 0;
    
    _searchBtn = [UIButton setButtonWithImage:@"" cornerRadius:0 backColor:[UIColor clearColor]];
    [self addSubview:_searchBtn];
    [_searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.width.height.offset(72);
        make.centerY.equalTo(_on_offBtn);
    }];
    [_searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _searchingIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Device_search"]];
    _searchBtn.layer.cornerRadius = 25;
    _searchBtn.clipsToBounds = YES;
    _searchBtn.layer.borderWidth = 1;
    _searchBtn.layer.borderColor = rgba(0.67, 0.67, 0.67, 1).CGColor;
    [_searchBtn addSubview:_searchingIcon];
    [_searchingIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(_searchBtn);
        make.width.height.offset(40);
    }];
    
    _closeTrunk = [UIButton setButtonWithImage:@"Device_Trunk_open" cornerRadius:0 backColor:[UIColor clearColor]];
    [self addSubview:_closeTrunk];
    [_closeTrunk mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-24);
        make.width.height.offset(72);
        make.centerY.equalTo(_on_offBtn);
    }];
    [_closeTrunk addTarget:self action:@selector(closeTrunkClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)closeTrunkClick{
    UserInfo *user = USERINFO;
    if(user.token.length < 1){
        [[UserInfoManager sharedInstance] loginOut];
        return;
    }
    if([self showError]){
        return;
    }
    if(!_deviceInfo.is_show_couch){
        [[KRAlartManager shareInstance] showAlert:@"该车型不支持座舱锁功能"];
        return;
    }
    [KeRenRequestTool deviceTruck:self.deviceInfo bleSuccess:^(BOOL netSuccess, BOOL status) {
        [[KRAlartManager shareInstance] showAlert:@"座垫已弹出"];
    } failure:^(BOOL netFailure) {
            
    }];
}

- (void)setPower_status:(BOOL)network{
    if(network){
        if([UserInfoManager sharedInstance].currentDeviceInfo.online_status){
            if([UserInfoManager sharedInstance].currentDeviceInfo.power_status == 0){
                [self seton_offBtnStatus:NO isrequest:NO];
            }else if([UserInfoManager sharedInstance].currentDeviceInfo.power_status == 2){
                [self seton_offBtnStatus:YES isrequest:NO];
            }
        }
    }else{
        WEAKSELF
        [HABleManager bleQueryOpenStatus:^(HABleModel * _Nonnull bleModel) {
            int power_status = [bleModel power_status];
            if(power_status == 1 || power_status == 17){
                power_status = 2;
            }else{
                power_status = 0;
            }
            [UserInfoManager sharedInstance].currentDeviceInfo.power_status = power_status;
            if(power_status == 2){
                [weakSelf seton_offBtnStatus:YES isrequest:NO];
            }else{
                [weakSelf seton_offBtnStatus:NO isrequest:NO];
            }
        }];
    }
}

- (void)searchBtnClick{
    UserInfo *user = USERINFO;
    WEAKSELF
    if(user.token.length < 1){
        [[UserInfoManager sharedInstance] loginOut];
        return;
    }
    if(![self showError]){
        if(!_isSearch){
            weakSelf.isSearch = YES;
        }else{
            _isSearch = NO;
            [_searchingIcon.layer removeAllAnimations];
            _searchingIcon.image = [UIImage imageNamed:@"Device_search"];
        }
        WEAKSELF
        if(_isSearch){
            [KeRenRequestTool deviceSearch:self.deviceInfo bleSuccess:^(BOOL netSuccess, BOOL status) {
                [weakSelf playVoiceAn];
            } failure:^(BOOL netFailure) {
                        
            }];
        }else{
            [KeRenRequestTool deviceEndSearch:self.deviceInfo bleSuccess:^(BOOL netSuccess, BOOL status) {
                        
            } failure:^(BOOL netFailure) {
                        
            }];
        }
    }
}

- (void)playVoiceAn{
    WEAKSELF
    weakSelf.isSearch = YES;
    weakSelf.searchingIcon.image = [UIImage imageNamed:@"Device_center_searching"];
    CABasicAnimation *animation =  [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //默认是顺时针效果，若将fromValue和toValue的值互换，则为逆时针效果
    animation.fromValue = [NSNumber numberWithFloat:0.f];
    animation.toValue =  [NSNumber numberWithFloat: M_PI *2];
    animation.duration  = 1;
    animation.autoreverses = NO;
    animation.fillMode =kCAFillModeForwards;
    animation.repeatCount = MAXFLOAT; //如果这里想设置成一直自旋转，可以设置为MAXFLOAT，否则设置具体的数值则代表执行多少次
    [weakSelf.searchingIcon.layer addAnimation:animation forKey:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(weakSelf.isSearch){
            weakSelf.isSearch = NO;
            [weakSelf.searchingIcon.layer removeAllAnimations];
            weakSelf.searchingIcon.image = [UIImage imageNamed:@"Device_search"];
        }
    });

}


-(void)firing{
    UserInfo *user = USERINFO;
    if(user.token.length < 1){
        [[UserInfoManager sharedInstance] loginOut];
        return;
    }
    if([self showError] && [UserInfoManager sharedInstance].currentDeviceInfo.sn_code == nil){
        return;
    }
    
    DDLogInfo(@"=======bleConnected characteristic is1: %d",_isOn);
    WEAKSELF
    if(!_isOn){
        //TODO: 国际化
        [UIView animateWithDuration:1 animations:^{
            weakSelf.firingImageView.alpha = 1;
            [weakSelf.on_offBtn setTitle:@"启动中" forState:UIControlStateNormal];
            [weakSelf.on_offBtn setTitleColor:Whire_Color forState:UIControlStateNormal];
            weakSelf.on_offBtn.titleLabel.font = BFont(16);
            [weakSelf.on_offBtn setImage:nil forState:UIControlStateNormal];
        } completion:^(BOOL finished) {
            //weakSelf.on_offBtn.alpha = 1;
            CABasicAnimation *animation =  [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
            //默认是顺时针效果，若将fromValue和toValue的值互换，则为逆时针效果
            animation.fromValue = [NSNumber numberWithFloat:0.f];
            animation.toValue =  [NSNumber numberWithFloat: M_PI *2];
            animation.duration  = 1.5;
            animation.autoreverses = NO;
            animation.fillMode =kCAFillModeForwards;
            animation.repeatCount = MAXFLOAT; //如果这里想设置成一直自旋转，可以设置为MAXFLOAT，否则设置具体的数值则代表执行多少次
            [weakSelf.firingImageView.layer addAnimation:animation forKey:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if(weakSelf.isLoding){
                    [weakSelf seton_offBtnStatus:NO isrequest:NO];
                    weakSelf.on_offBtn.enabled = YES;
                }
            });
        }];
    }
    _isLoding = YES;
    _on_offBtn.enabled = NO;
    
    [self contentAgain];
//    [self didDevicePowerChange];
}
//启动指令
- (void)didDevicePowerChange{
    WEAKSELF
    DDLogInfo(@"=======bleConnected characteristic is2: %d",_isOn);
    [KeRenRequestTool devicePowerChange:self.deviceInfo status:_isOn ? 1 : 0 bleSuccess:^(BOOL netSuccess, BOOL status) {
        weakSelf.isLoding = NO;
        weakSelf.on_offBtn.enabled = YES;
        DDLogInfo(@"=======bleConnected characteristic is3: %d -- %d",weakSelf.isOn,status);
        if(status){
            weakSelf.isOn = !weakSelf.isOn;
            [weakSelf seton_offBtnStatus:weakSelf.isOn isrequest:YES];
        }else{
            [weakSelf seton_offBtnStatus:weakSelf.isOn isrequest:NO];
        }
    } failure:^(BOOL netFailure) {
        if(netFailure){
            weakSelf.on_offBtn.enabled = YES;
        }else{
            weakSelf.isLoding = NO;
            weakSelf.on_offBtn.enabled = YES;
            [weakSelf seton_offBtnStatus:weakSelf.isOn isrequest:NO];
        }
    }];
}

- (void)contentAgain{
    WEAKSELF
    DDLogInfo(@"=======bleConnected characteristic is: 05");
    NSString*coded = [UserInfoManager sharedInstance].currentDeviceInfo.sn_code;
    CBPeripheral *peripheral = [HABleManager checkBleConnectedPeripheral:coded];
    if(peripheral == nil){
        [KeRenBleTool scanAndConnectedBLE:coded callBack:^(BOOL success) {
            DDLogInfo(@"=======bleConnected characteristic is: 03");
//            if(!weakSelf.contenting)[weakSelf didDevicePowerChange];
            weakSelf.contenting++;
            if(weakSelf.contenting == 2){
                DDLogInfo(@"=======bleConnected characteristic is: 010");
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf didDevicePowerChange];
                    weakSelf.contenting = 0;
                });
                
            }
            
        }];
    }else{
        DDLogInfo(@"=======bleConnected characteristic is: 04");
        [self didDevicePowerChange];
    }
}


- (void)seton_offBtnStatus:(BOOL)status isrequest:(BOOL)isrequest{
    self.isOn = status;
    [self.firingImageView.layer removeAllAnimations];
    self.firingImageView.alpha = 0;
    if(status){
        if(isrequest)
        {
            [[KRAlartManager shareInstance] showAlert:@"启动完成"];
        }
        [self.on_offBtn setTitle:nil forState:UIControlStateNormal];
        [self.on_offBtn setImage:[UIImage imageNamed:@"device_on_green"] forState:UIControlStateNormal];
    }else{
        if(isrequest)
        {
            [[KRAlartManager shareInstance] showAlert:@"已关闭"];
        }
        self.on_offBtn.backgroundColor = [UIColor clearColor];
        [self.on_offBtn setImage:[UIImage imageNamed:@"Device_on"] forState:UIControlStateNormal];
        _isOn = NO;
    }
}

-(void)changePowerBtnStatus:(BOOL)status{
    [self seton_offBtnStatus:status isrequest:NO];
}

-(void)resetLayout{
    if(self.deviceInfo){
        DeviceConfig *config = self.deviceInfo.deviceConfig;
        self.on_offBtn.hidden = !config.start_off;
        self.searchBtn.hidden = !config.find_bike;
        self.closeTrunk.hidden = !config.cushion;
    }else{
        self.on_offBtn.hidden = NO;
        self.searchBtn.hidden = NO;
        self.closeTrunk.hidden = NO;
    }
   
}

-(void)setDeviceInfo:(DeviceInfo *)deviceInfo{
    if(_deviceInfo != deviceInfo){
        _deviceInfo = deviceInfo;
        NSMutableArray *arr = @[].mutableCopy;
        SmartItem *item = [SmartItem createSmartItem:@"服务网点" imgName:@"service_etwork_icon" type:SmartType_Service_Network];
        [arr addObject:item];
        if(_deviceInfo.deviceConfig.electric_fence){
            item = [SmartItem createSmartItem:@"电子围栏" imgName:@"electronic_fence" type:SmartType_Fence];
            [arr addObject:item];
        }
        
        item = [SmartItem createSmartItem:@"钥匙分享" imgName:@"Key_sharing" type:SmartType_Key_Share];
        [arr addObject:item];
        
        item = [SmartItem createSmartItem:@"骑行导航" imgName:@"cycling_navigation" type:SmartType_Ride_Navigation];
        [arr addObject:item];
        
        if(_deviceInfo.deviceConfig.bike_location){
            item = [SmartItem createSmartItem:@"车辆位置" imgName:@"Vehicle Location" type:SmartType_Veh_Location];
            [arr addObject:item];
        }
        
        if(_deviceInfo.deviceConfig.ride_statistics || _deviceInfo.deviceConfig.track_list){
            item = [SmartItem createSmartItem:@"骑行记录" imgName:@"Ride_Record" type:SmartType_Ride_Record];
            [arr addObject:item];
        }
        self.dataArray = arr;
        [self.collectionV reloadData];
        [self resetLayout];
    }
}


- (BOOL)showError{
    if(!self.deviceInfo){
        [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆后再进行操作"];
        return YES;
    }
    if(_deviceInfo.lock_status == 0 && [self.deviceInfo is4GDevice]){
        [[KRAlartManager shareInstance] showErrorAlert:@"车辆已锁定"];
        return YES;
    }
    CBPeripheralState state = [HABleManager checkBleConnectedState:self.deviceInfo.sn_code];
    if([self.deviceInfo is4GDevice] && self.deviceInfo.online_status == 0 && state != CBPeripheralStateConnected){
        [[KRAlartManager shareInstance] showErrorAlert:@"车辆已离线"];
        return YES;
    }else if(![self.deviceInfo is4GDevice] && state != CBPeripheralStateConnected){
        [[KRAlartManager shareInstance] showErrorAlert:@"车辆已离线"];
        return YES;
    }
    return NO;
}

#pragma mark- UICollectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSUInteger count = self.dataArray.count >= 3 ? 3 : self.dataArray.count;
    return CGSizeMake((DEVICE_WIDTH-48)/(count * 1.0), 72);
}

#pragma mark- UICollectionViewDataSource
- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    KeRenHCollectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"KeRenHCollectCell" forIndexPath:indexPath];
    SmartItem *item = self.dataArray[indexPath.item];
    cell.titleLb.text = item.title;
    cell.imgV.image = [UIImage imageNamed:item.imgName];
    cell.lineV.hidden = (indexPath.item == self.dataArray.count - 1);
    [[ViewManager shareInstance] setLineBackLayerForView:cell.lineV];
    return cell;
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    SmartItem *item = self.dataArray[indexPath.item];
    UserInfo *user = USERINFO;
    if(user.token.length < 1){
        [[UserInfoManager sharedInstance] loginOut];
        return;
    }
    if(item.type == SmartType_Service_Network){
        ServiceNetworkVC *vc = [[ServiceNetworkVC alloc] init];
        [[ClassManager shareInstance].currentViewController.navigationController pushViewController:vc animated:YES];
    }else if(item.type == SmartType_Fence){
        if(![UserInfoManager sharedInstance].currentDeviceInfo){
            [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆后再进行操作"];
        }else{
            if(![UserInfoManager sharedInstance].currentDeviceInfo){
                [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆后再进行操作"];
                return;
            }
            if(_deviceInfo.online_status == 0 && [_deviceInfo is4GDevice]){
                [[KRAlartManager shareInstance] showErrorAlert:@"车辆已离线"];
                return;
            }
            if(!_deviceInfo.is_manager){
                [[KRAlartManager shareInstance] showAlert:@"该功能仅对车主开放"];
            }else{
                ElectronicfenceVC *vc = [[ElectronicfenceVC alloc] init];
                [[ClassManager shareInstance].currentViewController.navigationController pushViewController:vc animated:YES];
            }
        }
    }else if(item.type == SmartType_Key_Share){
        if(![UserInfoManager sharedInstance].currentDeviceInfo){
            [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆后再进行操作"];
        }else{
            if(!_deviceInfo.is_manager){
                [[KRAlartManager shareInstance] showAlert:@"该功能仅对车主开放"];
            }else{
                DeviceShareVC *vc = [[DeviceShareVC alloc] init];
                vc.deviceInfo = [UserInfoManager sharedInstance].currentDeviceInfo;
                [[ClassManager shareInstance].currentViewController.navigationController pushViewController:vc animated:YES];
            }
        }
    }else if(item.type == SmartType_Ride_Navigation){
        if(![UserInfoManager sharedInstance].currentDeviceInfo){
            [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆后再进行操作"];
        }else{
            DeviceNavcationVC *vc = [[DeviceNavcationVC alloc] init];
            [[ClassManager shareInstance].currentViewController.navigationController pushViewController:vc animated:YES];
        }
    }else if(item.type == SmartType_Veh_Location){
        DeviceLocationVC *vc = [[DeviceLocationVC alloc] init];
        [[ClassManager shareInstance].currentViewController.navigationController pushViewController:vc animated:YES];
    }else if(item.type == SmartType_Ride_Record){
        if(![UserInfoManager sharedInstance].currentDeviceInfo){
            [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆后再进行操作"];
        }else{
            DeviceCyclingRecordVC *vc = [[DeviceCyclingRecordVC alloc] init];
            [[ClassManager shareInstance].currentViewController.navigationController pushViewController:vc animated:YES];
        }
    }
}

#pragma mark- noti
-(void)changePowerStatus:(NSNotification *)noti{
    HABleModel *ble_Model = noti.object;
    int power_status = [ble_Model power_status];
    if(power_status == 1 || power_status == 17){
        power_status = 2;
    }else{
        power_status = 0;
    }
    [UserInfoManager sharedInstance].currentDeviceInfo.power_status = power_status;
    if(power_status == 2){
        [self seton_offBtnStatus:YES isrequest:NO];
    }else{
        [self seton_offBtnStatus:NO isrequest:NO];
    }
}
@end
